package com.mikasa.springboot.producer;

import java.util.Map;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import com.mikasa.springboot.entity.Order;

import javax.annotation.Resource;

/**
 * 消息发送类
 * @author mikasa
 */
@Component
public class RabbitSender {

	/**
	 * 消息模版类，需要去配置类或者配置文件中加入进Spring容器
	 */
	@Resource
	private RabbitTemplate rabbitTemplate;

	/**
	 * confirm确认的回调函数
	 */
	final ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {

		/**
		 * @param correlationData 回调的相关数据
		 * @param ack	ack结果 true/false
		 * @param cause nack的原因
		 */
		@Override
		public void confirm(CorrelationData correlationData, boolean ack, String cause) {
			System.err.println("correlationData: " + correlationData);
			System.err.println("ack: " + ack);
			if(!ack){
				System.err.println("异常处理....");
			}
		}
	};

	/**
	 * return返回未成功路由消息的回调函数
	 */
	final ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
		@Override
		public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
									String exchange, String routingKey) {
			System.err.println("return exchange: " + exchange + ", routingKey: " 
				+ routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
		}
	};

	/**
	 * 发送消息方法调用: 构建Message消息
	 * @param message
	 * @param properties
	 * @throws Exception
	 */
	public void send(Object message, Map<String, Object> properties) throws Exception {
		// 自定义携带的消息
		MessageHeaders mhs = new MessageHeaders(properties);
		Message msg = MessageBuilder.createMessage(message, mhs);
		rabbitTemplate.setConfirmCallback(confirmCallback);
		rabbitTemplate.setReturnCallback(returnCallback);
		// 是消息确认的唯一ID ：要保证全局唯一 id+时间戳，要根据这个ID找到唯一一条消息
		CorrelationData correlationData = new CorrelationData("1234567890");
		rabbitTemplate.convertAndSend("exchange-1", "springboot.abc", msg, correlationData);
	}

	/**
	 * 发送消息方法调用: 构建自定义对象消息
	 * @param order
	 * @throws Exception
	 */
	public void sendOrder(Order order) throws Exception {
		rabbitTemplate.setConfirmCallback(confirmCallback);
		rabbitTemplate.setReturnCallback(returnCallback);
		//id + 时间戳 全局唯一 
		CorrelationData correlationData = new CorrelationData("0987654321");
		rabbitTemplate.convertAndSend("exchange-2", "springboot.def", order, correlationData);
	}
	
}
